package com.github.xzb617.adm.service.impl;

import com.github.xzb617.adm.dao.FlowRuleMapper;
import com.github.xzb617.adm.service.FlowRuleService;
import com.github.xzb617.domain.entity.FlowRule;
import com.github.xzb617.security.SubjectHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class FlowRuleServiceImpl implements FlowRuleService {

    private final FlowRuleMapper flowRuleMapper;

    public FlowRuleServiceImpl(FlowRuleMapper flowRuleMapper) {
        this.flowRuleMapper = flowRuleMapper;
    }

    @Override
    public List<FlowRule> getListByFlowId(Integer flowId) {
        Example example = new Example(FlowRule.class);
        example.createCriteria().andEqualTo("flowId", flowId);
        return this.flowRuleMapper.selectByExample(example);
    }

    @Override
    @Transactional
    public void update(Integer flowId, List<FlowRule> rules) {
        // 批量删除
        this.deleteByFlowId(flowId);
        // 批量新增 TODO 后续需要实现真的批量新增
        for (FlowRule rule : rules) {
            rule.setId(null);
            rule.setFlowId(flowId);
            rule.setCreateTime(new Date());
            rule.setCreateUser(SubjectHolder.getContext().getUsername());
            this.flowRuleMapper.insertSelective(rule);
        }
    }

    @Override
    @Transactional
    public void deleteByFlowId(Integer flowId) {
        Example example = new Example(FlowRule.class);
        example.createCriteria().andEqualTo("flowId", flowId);
        this.flowRuleMapper.deleteByExample(example);
    }
}
